<template>
  <div class="world" :style="`filter: brightness(${bright});`">
    <AreaBlock
      :show="item.show"
      :x="item.x"
      :y="item.y"
      v-for="item in areaBlockList"
      :key="String(item.x + ',' + item.y)"
    />
    <slot></slot>
  </div>
</template>

<script>
import AreaBlock from "@/components/world/AreaBlock.vue";
import { getAreaBlockByPosition } from "@/util/block.js";
import { isEmpty } from "@/util/common.js";
import { mapState } from "vuex";
import { getTimeByMin, getBrightnessByTime } from "@/util/time.js";

export default {
  components: { AreaBlock },
  data() {
    return {
      areaBlockList: {
        // "0,0": {
        //   show: true,
        //   x: 0,
        //   y: 0,
        // },
      },
    };
  },
  computed: {
    ...mapState("map", ["system", "mapTime"]),
    d() {
      return this.system.areaBlockDiameter;
    },
    bright() {
      let time = getTimeByMin(this.mapTime);
      return getBrightnessByTime(time.h, time.m);
    },
  },
  methods: {
    // 更新显示区块
    updateAreaBlock(x, y) {
      let position = getAreaBlockByPosition(x, y, this.d);
      let str = position.x + "," + position.y;

      if (isEmpty(this.areaBlockList[str])) {
        this.$set(this.areaBlockList, str, {
          show: true,
          x: position.x,
          y: position.y,
        });
      } else {
        this.areaBlockList[str].show = true;
      }
    },
    // 删除超远的区块
    removeAreaBlock(x, y) {
      const num = this.system.areaBlockHideDistance * this.d;

      let position = getAreaBlockByPosition(x, y, this.d);

      for (let key in this.areaBlockList) {
        let item = this.areaBlockList[key];
        if (
          Math.abs(item.x - position.x) > num ||
          Math.abs(item.y - position.y) > num
        ) {
          this.areaBlockList[key].show = false;
        }
      }
    },
  },
  mounted() {
    this.$bus.$on("updateAreaBlock", (x, y) => {
      this.updateAreaBlock(x, y);

      let n = this.system.areaBlockRenderDistance;
      // 从(x-n*d, y-n*d)到(x+n*d, y+n*d)渲染区块
      for (let i = -n; i <= n; i += 1) {
        for (let j = -n; j <= n; j += 1) {
          this.updateAreaBlock(x + i * this.d, y + j * this.d);
        }
      }

      // 清理区块
      this.removeAreaBlock(x, y);
    });
  },
};
</script>

<style scoped>
.world {
  position: relative;
  /* 近视 */
  /* filter: blur(5px); */
  /* 夜晚 */
  /* filter: brightness(0.3); */
}
</style>